/*
 * @Author: your name
 * @Date: 2021-08-12 09:07:53
 * @LastEditTime: 2021-11-17 14:13:03
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \li-yuwei\demo-work\src\router\index.js
 */
import Vue from "vue";
import VueRouter from "vue-router";
import cookie from "js-cookie";
import store from "../store/index";
Vue.use(VueRouter);
const routes = [{
        path: "/",
        redirect: "/login",
    },
    {
        path: "/login",
        name: "Login",
        component: () =>
            import ("../views/login/index.vue"),
    },
    {
        path: "/register",
        name: "Register",
        component: () =>
            import ("../views/register/index.vue"),
    },
    //文章详情
    {
        path: "/article/:id",
        name: "ArticleDetail",
        component: () =>
            import ("../views/articleDetail/index.vue"),
    },
    //页面详情
    {
        path: "/pageDetail/:id",
        name: "PageDetail",
        component: () =>
            import ("../views/pageDetail/index.vue"),
    },
    //知识小册详情
    {
        path: "/knowledgeDetail/:id",
        name: "KnowledgeDetail",
        component: () =>
            import ("../views/knowledgeDetail/index.vue"),
    },
];
const router = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    routes,
});
//判断本地存储中是否有数据
let userData = JSON.parse(window.localStorage.getItem("userData"));
let role;
if (userData) {
    role = userData.identity;
} else {
    role = "访客";
}
router.beforeEach((to, from, next) => {
    const token = cookie.get("token");
    if (to.path == "/login") {
        next();
        cookie.remove("token");
    } else if (to.path == "/register") {
        next();
        cookie.remove("token");
    } else {
        if (token && userData) {
            if (store.state.Routers.length <= 0) {
                store.dispatch("getRouters", role);
                next({...to, replace: true });
            } else {
                next();
            }
        } else {
            next("/login");
        }
    }
});
export default router;